<?php
/**
 * Description
 * User: duanwenjie
 * Date: 2019/5/15
 * Time: 12:09 PM
 */

namespace app\index\service;
use app\common\model\ToolModel;
use app\index\model\PurchaseplanfollowModel;
use think\Db;
use think\Exception;

class TasksService
{
    static public $over_time = 3600;

    /**
     * 抓取进销存 upload_batch_skus、upload_batch_details、purchaseorders、purchaseorder_details 四张表数据同步到YUJISO
     * 每十分钟执行一次同步任务
     * 规则：抓取 store_id = 7 && create_time = 最近一小时的数据 （防止漏数据）
     * @param array $param
     * @throws Exception
     * @author duanwenjie
     */
    static public function syncNewErpPrToYujiso($param = array())
    {
        try{
//            /*走接口获取进销存相关数据*/
//            $url = config('apiNewErpUrl') . 'commonapi/yujiso/syncPrToYujiso';
//            $response = curl($url, json_encode($param), array('Content-Type: application/json'));
//            $json = json_decode($response, true);
//            if (!$json || !isset($json['code']) || $json['code'] !== '000001'){
//                trace('url=' . $url . ',param=' . json_encode($param) . 'response=' . $response, 'error');
//                $json['data'] = array();
//            }
//            $data = $json['data'];
            set_time_limit(self::$over_time);
            $data = self::syncPrToYujiso($param);
            // 执行批量插入数据处理
            $upload_batch_skus_insertData = array();
            $upload_batch_details_insertData = array();
            $purchaseorders_insertData = array();
            $purchaseorder_details_insertData = array();
            if (!empty($data)){
                $upload_batch_skus = isset($data['upload_batch_skus']) ? $data['upload_batch_skus'] : array();
                $upload_batch_details = isset($data['upload_batch_details']) ? $data['upload_batch_details'] : array();
                $purchaseorders = isset($data['purchaseorders']) ? $data['purchaseorders'] : array();
                $purchaseorder_details = isset($data['purchaseorder_details']) ? $data['purchaseorder_details'] : array();
                if (!empty($upload_batch_skus)) $upload_batch_skus_insertData = $upload_batch_skus;
                if (!empty($upload_batch_details)) $upload_batch_details_insertData = $upload_batch_details;
                if (!empty($purchaseorders)) $purchaseorders_insertData = $purchaseorders;
                if (!empty($purchaseorder_details)) $purchaseorder_details_insertData = $purchaseorder_details;
            }
            // 批量插入表 hz_purchaseorder_details hz_purchaseorders hz_upload_batch_details hz_upload_batch_skus 数据
            $res = $res2 = $res3 = $res4 = $res5 = $res6 = 0;
            if (!empty($upload_batch_skus_insertData)){
                $res = ToolModel::dbInsertOrUpdate('hz_upload_batch_skus', $upload_batch_skus_insertData);
            }
            if (!empty($upload_batch_details_insertData)){
                $res2 = ToolModel::dbInsertOrUpdate('hz_upload_batch_details', $upload_batch_details_insertData);
            }
            if (!empty($purchaseorders_insertData)){
                $res3 = ToolModel::dbInsertOrUpdate('hz_purchaseorders', $purchaseorders_insertData);
            }
            if (!empty($purchaseorder_details_insertData)){
                $res4 = ToolModel::dbInsertOrUpdate('hz_purchaseorder_details', $purchaseorder_details_insertData);
            }

            /*同步完毕进销存数据，更新采购计划 purchase_plan 表的 unusual_reason、po、pr_state 字段*/
            $sql = " SELECT PP.id,HZUBD.real_purchaseorder_id as po,HZUBS.check_result as unusual_reason,HZUBS.status as pr_state
                     FROM purchase_plan PP LEFT JOIN hz_upload_batch_skus HZUBS ON PP.pr = HZUBS.id
                     LEFT JOIN hz_upload_batch_details HZUBD ON HZUBS.details_id = HZUBD.id";
            $update_data = ToolModel::queryData($sql);
            if (!empty($update_data)) $res5 = ToolModel::dbInsertOrUpdate('purchase_plan',$update_data);


            // 更新完以上数据库信息，再执行插入PO提货明细数据到 draw_po_detail 操作
            $draw_po_detail_insertData = Db::name('hz_purchaseorders')->alias('HZP')
                ->join('draw_plan DP','HZP.id = DP.po','right')
                ->join('hz_purchaseorder_details HZPD','HZP.id = HZPD.purchaseorder_id AND DP.sku = HZPD.sku','left')
                ->field('DP.po,DP.po_quantity,DP.sku,DP.sku_name,SUM(DP.present_quantity)as draw_quantity,
                (DP.po_quantity - SUM(DP.present_quantity))as surplus_quantity,HZPD.ware_quantity as in_quantity,HZPD.status')
                ->group('HZP.id,DP.sku')
                ->select();
            if (!empty($draw_po_detail_insertData)) $res6 = ToolModel::dbInsertOrUpdate('draw_po_detail',$draw_po_detail_insertData);

            // 插入日志
            $operator =  CN_NAME ? CN_NAME : 'admin';
            $param_ = json_encode($param);
            $data_logs = array(
                "type" => 1,
                "status" => 1,
                "method" => "Tasks::syncNewErpPrToYujiso",
                "message" => "拉取进销存采购计划,hz_upload_batch_skus 表中受影响的行数为：{$res},
                          hz_upload_batch_details 表中受影响的行数为：{$res2},
                          hz_purchaseorders 表中受影响的行数为：{$res3},
                          hz_purchaseorder_details 表中受影响的行数为：{$res4}
                          purchase_plan 表中受影响的行数为：{$res5}
                          draw_po_detail 表中受影响的行数为：{$res6}",
                "request" => "operator = {$operator},params = {$param_}"
            );
            ToolModel::saveApiLogs($data_logs);
            returnJson(1, '操作成功');
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            $data_logs = array(
                "type" => 1,
                "status" => 0,
                "method" => "Tasks::syncNewErpPrToYujiso",
                "message" => "拉取进销存采购计划失败：原因=> ".$e->getMessage(),
            );
            ToolModel::saveApiLogs($data_logs);
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 进销存数据来源改为从数据库直接读取，不走接口获取数据形式
     * @param array $param
     * @return array
     * @throws Exception
     * @author duanwenjie
     */
    static public function syncPrToYujiso($param = array())
    {
        try{
            /*抓取 upload_batch_skus 表数据*/
            $where = " where 1 = 1 AND UBS.warehouse_id = 7"; // 抓取仓库id为7的数据
            $create_time = date("Y-m-d H:i:s", strtotime("-1 hour")); // 时间间隔为当前时间以前1小时
            if (!empty($param)){
                if (isset($param['create_time']) && !empty($param['create_time'])) $where .= " AND UBS.create_time >= '{$param['create_time']}'";
                if (isset($param['end_time']) && !empty($param['create_time'])) $where .= " AND UBS.create_time <= '{$param['end_time']}'";
            }else{
                $where .= " AND UBS.create_time >= '{$create_time}'";
            }
            $sql = "SELECT * FROM upload_batch_skus UBS {$where}";
            $res = Db::connect('newerp')->query($sql);

            /*抓取 upload_batch_details 表数据 */
            $res2 = array();
            $where2 = " where 1 = 1";
            if (!empty($res)){
                $details_id_arr = array_column(array_values($res), 'details_id');
                $details_id_arr = array_map(function ($n){
                    return "'" . addslashes(trim($n)) . "'";
                }, $details_id_arr);
                $details_ids = implode(",", $details_id_arr);
                $where2 .= " AND UBD.id IN ({$details_ids})";
                $sql2 = "SELECT * FROM upload_batch_details UBD {$where2}";
                $res2 = Db::connect('newerp')->query($sql2);
            }

            /*抓取 purchaseorders purchaseorder_details 表数据 */
            $res3 = array();
            $res4 = array();
            $where3 = " where 1 = 1";
            $where4 = " where 1 = 1";
            if (!empty($res2)){
                $purchaseorders_id_arr = array_filter(array_column(array_values($res2), 'real_purchaseorder_id'));
                if (!empty($purchaseorders_id_arr)){
                    $purchaseorders_id_arr = array_map(function ($n){
                        return "" . addslashes(trim($n)) . "";
                    }, $purchaseorders_id_arr);
                    $purchaseorders_ids = implode(",", $purchaseorders_id_arr);
                    /*主表数据*/
                    $where3 .= " AND P.id IN ({$purchaseorders_ids})";
                    $sql3 = "SELECT * FROM purchaseorders P {$where3}";
                    $res3 = Db::connect('newerp')->query($sql3);
                    /*明细数据*/
                    $where4 .= " AND PD.purchaseorder_id IN ({$purchaseorders_ids})";
                    $sql4 = "SELECT * FROM purchaseorder_details PD {$where4}";
                    $res4 = Db::connect('newerp')->query($sql4);
                }
            }

            $data = array("upload_batch_skus" => $res, "upload_batch_details" => $res2, "purchaseorders" => $res3, "purchaseorder_details" => $res4);
            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 更新店铺销售库存分析报表数据
     * @throws Exception
     * @author duanwenjie
     */
    static public function updateShopSaleStockData()
    {
        try{
            // == 店铺销售库存分析报表字段统计 == //
            // apply_quantity => 申请数量 = 采购计划累计的实际未下单数量之和（未生成PO的单的数量之和）
            // po_way_quantity => 采购在途 = PO数量 - 累计的实际提货数量之和
            // transfer_warehouse_stock => 中转仓库存 = 累计的入库数量之和 - 发运计划的累计出库数量之和
            // ship_way_quantity => 发运在途 = 发运计划累计的签收数量 - 发运计划累计的出库数量（发货数量）
            // country_stock_quantity => 国家仓库存 = 国家仓入库数量 - 调拨单调拨数量
            // shop_stock => 店仓库存 = 店仓库存管理实物库存数量
            // draw_way_quantity => 提货在途 = 累计的实际提货数量之和 - 已入库数量 （actual_quantity_all => 累计的实际提货数量之和 warequantity => 已入库数量）

            set_time_limit(self::$over_time);
            $res = Db::table('purchase_plan')->alias('PP')
                ->join('draw_plan_detail DPD','PP.base_shop_id = DPD.base_shop_id','left')
                ->join('draw_plan DP','PP.sku = DP.sku AND DP.id = DPD.draw_plan_id','left')
                ->join('base_shop BS','PP.base_shop_id = BS.id','left')
                ->join('base_warehouse BW','BS.id = BW.base_shop_id','left')
                ->join('shop_warehouse_stock SWS','PP.sku = SWS.sku AND BW.id = SWS.base_warehouse_id','left')
                ->field('PP.po,PP.base_shop_id,BS.shop_name,PP.sku,PP.sku_name,SWS.physical_stock as shop_stock')
                ->where('PP.status','=',1)
                ->where('PP.base_shop_id','<>',0)
                ->group('PP.base_shop_id,PP.sku') // 店铺+SKU维度
                ->select();

            $data = self::convertData($res);
            /*更新shop_sale_stock 店铺销售库存分析报表数据*/
            $res_ = 0;
            if (!empty($data)) $res_ = ToolModel::dbInsertOrUpdate('shop_sale_stock', $data);
            // 插入日志
            $operator =  CN_NAME ? CN_NAME : '系统';
            $data_logs = array(
                "type" => 2,
                "status" => 1,
                "method" => "Tasks::updateShopSaleStockData",
                "message" => "更新店铺销售库存分析报表数据,shop_sale_stock 表中受影响的行数为：{$res_}",
                "request" => "operator = {$operator}"
            );
            ToolModel::saveApiLogs($data_logs);
            returnJson('1', '操作成功');
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            $data_logs = array(
                "type" => 2,
                "status" => 0,
                "method" => "Tasks::updateShopSaleStockData",
                "message" => "更新店铺销售库存分析报表数据失败：原因=> ".$e->getMessage(),
            );
            ToolModel::saveApiLogs($data_logs);
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 获取已入库数量、提货在途数量,整理字段值
     * @param array $data
     * @return array
     * @author duanwenjie
     */
    static public function convertData($data = array())
    {
        $purchase = PurchaseplanfollowModel::getPercentage();
        if ($data){
            $purchaseArr = array_unique(array_column($data, 'po'));
            $resultWare = \app\common\service\WarehouseService::getWarehouse($purchaseArr, '*', 'po_sku');
            $exist_sku_shop = array(); // sku_shop_id 为键，统计已存在的店铺SKU累计出库数量
            foreach ($data as &$value_){
                $po_sku = $value_['po'] . "_" . $value_['sku'];
                $wareinfo = isset($resultWare[$po_sku]) ? $resultWare[$po_sku] : [];
                $warehouseTotal = !empty($wareinfo) ? array_sum(array_column($wareinfo, 'warehouse_quantity')) : 0;
                $percentage = isset($purchase[$po_sku]['percentage']) ? $purchase[$po_sku]['percentage'] : 0;
                $str = $value_['sku'] . "_" . $value_['base_shop_id'];
                $warequantity = !empty($percentage) ? bcmul($percentage, intval($warehouseTotal)) : 0; // 入库数量
                if (in_array($str, array_keys($exist_sku_shop))){
                    $exist_sku_shop[$str] += $warequantity;
                }else{
                    $exist_sku_shop[$str] = $warequantity;
                }
                $temp_ = self::getDrawQuantity($value_['sku'], $value_['base_shop_id']);
                $value_['actual_quantity_all'] = isset($temp_['actual_quantity_all']) ? $temp_['actual_quantity_all'] : 0;
            }

            $po_quantity_all = self::getPoQuantityAll();
            foreach ($data as $key => &$value){
                $po_sku = $value['po'] . "_" . $value['sku'];
                $wareinfo = isset($resultWare[$po_sku]) ? $resultWare[$po_sku] : [];
                $warehouseTotal = !empty($wareinfo) ? array_sum(array_column($wareinfo, 'warehouse_quantity')) : 0;
                $percentage = isset($purchase[$po_sku]['percentage']) ? $purchase[$po_sku]['percentage'] : 0;
                $str = $value['sku'] . "_" . $value['base_shop_id'];
                $warequantity = !empty($percentage) ? bcmul($percentage, intval($warehouseTotal)) : 0;
                $value['draw_way_quantity'] = $value['actual_quantity_all'] - $warequantity; // 提货在途 = 累计的实际提货数量之和 - 已入库数量
                $sku = $value['sku'];
                $shop_id = $value['base_shop_id'];
                $res = self::getShipDeliverySendQuantity($sku, $shop_id);
                $value['ship_way_quantity'] = !empty($res) ? $res['ship_way_quantity'] : 0;
                $chuku_quantity = !empty($res) ? $res['chuku_quantity'] : 0;
                $value['transfer_warehouse_stock'] = isset($exist_sku_shop[$str]) ? $exist_sku_shop[$str] - $chuku_quantity : 0;
                $res2 = self::getCountryAllocateInQuantity($sku, $shop_id);
                $guojia_ruku_quantity = isset($res2[$str]['guojia_ruku_quantity']) ? $res2[$str]['guojia_ruku_quantity'] : 0; // 国家仓入库数量
                $diaobo_ruku_quantity = isset($res2[$str]['diaobo_ruku_quantity']) ? $res2[$str]['diaobo_ruku_quantity'] : 0; // 调拨单调拨数量
                $value['country_stock_quantity'] = $guojia_ruku_quantity - $diaobo_ruku_quantity;
                $apply_quantity = self::getApplyQuantity($sku, $shop_id);
                $value['apply_quantity'] = $apply_quantity;
                $temp = isset($po_quantity_all[$value['po']]) ? $po_quantity_all[$value['po']] : array();
                $po_quantity = isset($temp[$value['sku'] . "_" . $shop_id]) ? $temp[$value['sku'] . "_" . $shop_id] : 0;
                $value['po_way_quantity'] = $po_quantity - $value['actual_quantity_all'];
                unset($value['po'], $value['actual_quantity_all']);
            }
        }

        return $data;
    }


    /**
     * 获取签收、出库数量、发运在途 (店铺+SKU 总的统计数据)
     * @param $sku
     * @param $shop_id
     * @return false|\PDOStatement|string|\think\Collection
     * @author duanwenjie
     */
    static public function getShipDeliverySendQuantity($sku, $shop_id)
    {
        $res = Db::name('ship_plan_receive')->alias('SPR')
            ->join('ship_plan_send SPS','SPR.code = SPS.code AND SPR.shop_id = SPS.shop_id AND SPR.sku = SPS.sku','left')
            ->field('SUM(SPR.quantity) as qianshou_quantity,SUM(SPS.quantity) as chuku_quantity,(SUM(SPR.quantity) - SUM(SPS.quantity)) as ship_way_quantity')
            ->where('SPS.sku','=',$sku)
            ->where('SPS.shop_id','=',$shop_id)
            ->find();

        return $res;
    }

    /**
     * 获取国家仓入库数量、调拨单入库数量（店铺+SKU 总的统计数据）
     * @param $sku
     * @param $shop_id
     * @return array
     * @author duanwenjie
     */
    static public function getCountryAllocateInQuantity($sku, $shop_id)
    {
        /*国家仓累计的入库数量*/
        $res = Db::name('warehouse_country_detail')->alias('WCD')
            ->join('ship_plan_send SPS','WCD.shop_id = SPS.shop_id AND WCD.sku = SPS.sku','left')
            ->field('WCD.sku,WCD.quantity,SPS.shop_id')
            ->where('SPS.shop_id','=',$shop_id)
            ->where('WCD.sku','=',$sku)
            ->where('WCD.shop_id','<>','')
            ->group('WCD.warehouse_country_id,WCD.shop_id,WCD.sku')
            ->select();
        $exist_sku_shop_guojia = array();
        if (!empty($res)){
            foreach ($res as $value){
                $str = $value['sku'] . "_" . $value['shop_id'];
                if (in_array($str, array_keys($exist_sku_shop_guojia))){
                    $exist_sku_shop_guojia[$str]['guojia_ruku_quantity'] += $value['quantity'];
                }else{
                    $exist_sku_shop_guojia[$str]['guojia_ruku_quantity'] = $value['quantity'];
                }
            }
        }

        /*调拨单累计入库数量*/
        $res_ = Db::name('allocate_order')->alias('AO')
            ->join('allocate_order_detail AOD','AO.id = AOD.allocate_order_id','left')
            ->field('AO.base_shop_id,AOD.sku,AOD.quantity')
            ->where('AO.base_shop_id','=',$shop_id)
            ->where('AOD.sku','=',$sku)
            ->select();
        $exist_sku_shop_diaobo = array();
        if (!empty($res_)){
            foreach ($res_ as $value_){
                $str = $value_['sku'] . "_" . $value_['base_shop_id'];
                if (in_array($str, array_keys($exist_sku_shop_diaobo))){
                    $exist_sku_shop_diaobo[$str]['diaobo_ruku_quantity'] += $value_['quantity'];
                }else{
                    $exist_sku_shop_diaobo[$str]['diaobo_ruku_quantity'] = $value_['quantity'];
                }
            }
        }
        $data = array_merge_recursive($exist_sku_shop_diaobo, $exist_sku_shop_guojia);

        return $data;
    }

    /**
     * 更新库存管理库龄数据
     * @author duanwenjie
     */
    static public function updateStockAge()
    {
        $res = Db::name('shop_warehouse_stock')->select();
        $temp = array();
        if (!empty($res)){
            foreach ($res as $value){
                $value['stock_age'] += round((time() - strtotime($value['update_time'])) / 86400, 2); // 累加库龄数据 （旧的库龄 + 更新后的库龄）
                $temp[] = array(
                   "id" => $value['id'],
                   "update_time" => date('Y-m-d H:i:s'),
                   "stock_age" => $value['stock_age']
               );
            }
        }
        if (!empty($temp)) $res_ = ToolModel::dbInsertOrUpdate('shop_warehouse_stock', $temp);

        returnJson('1', '操作成功,受影响的行：'.count($res_));
    }

    /**
     * 获取申请数量
     * @param $sku
     * @param $shop_id
     * @return int
     * @author duanwenjie
     */
    static public function getApplyQuantity($sku, $shop_id)
    {
        $sql = "SELECT base_shop_id,sku,SUM(quantity) as apply_quantity FROM purchase_plan 
                WHERE id in (SELECT id FROM purchase_plan WHERE `status` = 1 AND base_shop_id <> 0 GROUP BY base_shop_id,sku) 
                AND pr_state = 0 GROUP BY base_shop_id,sku";
        $data = Db::query($sql);
        $apply_quantity = 0;
        if (!empty($data)){
            foreach ($data as $value){
                if ($value['sku'] == $sku && $value['base_shop_id'] == $shop_id) $apply_quantity = $value['apply_quantity'];
            }
        }

        return $apply_quantity;
    }


    /**
     * 获取店铺+SKU对应的PO数量（PR数量比例加权后）
     * @return array
     * @author duanwenjie
     */
    static public function getPoQuantityAll()
    {
        $sql = "SELECT PP.id,PP.base_shop_id,PP.sku,PP.po,HZPD.quantity as po_quantity,PP.pr,PP.pr_state,SUM(PP.quantity) 
                as pr_quantity_all FROM purchase_plan PP
                LEFT JOIN hz_purchaseorder_details HZPD ON PP.po = HZPD.purchaseorder_id AND PP.sku = HZPD.sku
                WHERE PP.id in (SELECT id FROM purchase_plan WHERE `status` = 1 AND base_shop_id <> 0 GROUP BY base_shop_id,sku) GROUP BY PP.pr";
        $data = Db::query($sql);
        $pr_quantity_all = array();
        $po_quantity = array(); // 店铺+SKU维度 pr单对应的PO数量（加权后）
        if (!empty($data)){
            $exist_po = array();
            foreach ($data as $value){
                if (in_array($value['po'], $exist_po)){
                    $pr_quantity_all[$value['po']] += $value['pr_quantity_all'];
                }else{
                    $exist_po[] = $value['po'];
                    $pr_quantity_all[$value['po']] = $value['pr_quantity_all'];
                }
            }
            $exist_sku_shop_id = array();
            foreach ($data as $value_){
                $key_ = $value_['sku'] . "_" . $value_['base_shop_id'];
                if (in_array($key_,$exist_sku_shop_id)){
                    if (isset($po_quantity[$value_['po']][$key_])){
                        $po_quantity[$value_['po']][$key_] += $value_['pr_quantity_all'] / $pr_quantity_all[$value_['po']] * $value_['po_quantity'];
                    }else{
                        $po_quantity[$value_['po']][$key_] = 0;
                    }
                }else{
                    $exist_sku_shop_id[] = $key_;
                    $po_quantity[$value_['po']][$key_] = $value_['pr_quantity_all'] / $pr_quantity_all[$value_['po']] * $value_['po_quantity'];
                }
            }
        }
        foreach ($po_quantity as &$v){
            ksort($v);
            foreach ($v as $k_ => &$v_){
                if ($v_ == reset($v)){
                    $v_ = ceil($v_);
                }else{
                    $v_ = floor($v_);
                }
            }
        }

        return $po_quantity;
    }


    /**
     * 获取累计的提货数量
     * @param $sku
     * @param $shop_id
     * @return array|false|\PDOStatement|string|\think\Model
     * @author duanwenjie
     */
    static public function getDrawQuantity($sku, $shop_id)
    {
        $res = Db::name('draw_plan')->alias('DP')
            ->join('draw_plan_detail DPD','DP.id = DPD.draw_plan_id','left')
            ->field('SUM(DPD.actual_quantity) as actual_quantity_all')
            ->where('DP.sku','=',$sku)
            ->where('DPD.base_shop_id','=',$shop_id)
            ->find();

        return $res;
    }

//    static public function updateShopSaleStockData2()
//    {
//        try{
//            // == 店铺销售库存分析报表字段统计 == //
//            // apply_quantity => 申请数量 = 累计的实际下单数量之和
//            // po_way_quantity => 采购在途 = 累计的实际提货数量之和
//            // transfer_warehouse_stock => 中转仓库存 = 累计的入库数量之和 - 发运计划的累计出库数量之和
//            // ship_way_quantity => 发运在途 = 发运计划累计的签收数量 - 发运计划累计的出库数量（发货数量）
//            // country_stock_quantity => 国家仓库存 = 国家仓入库数量 - 调拨单调拨数量
//            // shop_stock => 店仓库存 = 店仓库存管理实物库存数量
//            // draw_way_quantity => 提货在途 = 实际提货数量之和 - 已入库数量 （po_way_quantity => 实际提货数量之和 warequantity => 已入库数量）
//
//            set_time_limit(self::$over_time);
//            $res = Db::name('purchase_plan')->alias('PP')
//                ->join('draw_plan_detail DPD','PP.base_shop_id = DPD.base_shop_id','left')
//                ->join('draw_plan DP','PP.sku = DP.sku AND DP.id = DPD.draw_plan_id','left')
//                ->join('base_shop BS','PP.base_shop_id = BS.id','left')
//                ->join('base_warehouse BW','BS.id = BW.base_shop_id','left')
//                ->join('shop_warehouse_stock SWS','PP.sku = SWS.sku AND BW.id = SWS.base_warehouse_id','left')
//                ->field('PP.po,PP.base_shop_id,BS.shop_name,PP.sku,PP.sku_name,
//            SUM(PP.quantity) as apply_quantity,SUM(DPD.actual_quantity) as po_way_quantity,SWS.physical_stock as shop_stock')
//                ->where('PP.status','=',1)
//                ->where('PP.pr_state','=',1)
//                ->where('PP.base_shop_id','<>',0)
//                ->group('PP.base_shop_id,PP.sku') // 店铺+SKU维度
//                ->select();
//
//            $data = self::convertData($res);
//            /*更新shop_sale_stock 店铺销售库存分析报表数据*/
//            $res_ = 0;
//            if (!empty($data)) $res_ = ToolModel::dbInsertOrUpdate('shop_sale_stock', $data);
//            // 插入日志
//            $operator =  CN_NAME ? CN_NAME : '系统';
//            $data_logs = array(
//                "type" => 2,
//                "status" => 1,
//                "method" => "Tasks::updateShopSaleStockData",
//                "message" => "更新店铺销售库存分析报表数据,shop_sale_stock 表中受影响的行数为：{$res_}",
//                "request" => "operator = {$operator}"
//            );
//            ToolModel::saveApiLogs($data_logs);
//            returnJson('1', '操作成功');
//        }catch (Exception $e){
//            trace($e->getMessage(), 'error');
//            $data_logs = array(
//                "type" => 2,
//                "status" => 0,
//                "method" => "Tasks::updateShopSaleStockData",
//                "message" => "更新店铺销售库存分析报表数据失败：原因=> ".$e->getMessage(),
//            );
//            ToolModel::saveApiLogs($data_logs);
//            throw new Exception($e->getMessage());
//        }
//    }
}